/*
 * Copyright 1999-2017 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.p3c.pmd.lang.java.rule.comment;

import com.alibaba.p3c.pmd.I18nResources;
import com.alibaba.p3c.pmd.lang.java.util.ViolationUtils;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.*;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Pattern;

/**
 * [Mandatory] controller  should be commented by Javadoc.
 * Javadoc should include method instruction, description of parameters, return values and possible exception.
 *
 /**
 * @author zhaoyunlong
 * @date 2020/5/13
 * @description  检测controller层的类需要添加注释
 */

public class ControllerClassMustUseJavadocRule extends AbstractAliCommentRule {

    private static final String MESSAGE_KEY_PREFIX
        = "java.comment.ControllerClassMustUseJavadocRule.violation.msg";

    private static final Pattern EMPTY_CONTENT_PATTERN = Pattern.compile("[/*\\n\\r\\s]+(@.*)?", Pattern.DOTALL);

    static final String[] CONTROLLER_FLAG = {
            "controller",
            "Controller",
    };
    /**
     * Immediately return after visiting class/interface/enum/annotation,
     * so that we don't need to deal with inner class/interface/enum/annotation declarations.
     *
     * @param decl
     * @param data
     * @return
     */
    @Override
    public Object visit(ASTClassOrInterfaceDeclaration decl, Object data) {
        // If a CompilationUnit has multi class definition, only the public one will be checked.
        if (decl.isPublic()) {
            checkAuthorComment(decl, data);
        }
        return data;
    }

    @Override
    public Object visit(ASTEnumDeclaration decl, Object data) {
        // Exclude inner enum
        if (!decl.isPublic()) {
            return super.visit(decl, data);
        }

        // Inner enum should have author tag in outer class.
        ASTClassOrInterfaceDeclaration parent = decl.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
        if (parent != null) {
            return super.visit(decl, data);
        }

        checkAuthorComment(decl, data);
        return data;
    }

    @Override
    public Object visit(ASTAnnotationTypeDeclaration decl, Object data) {
        checkAuthorComment(decl, data);
        return data;
    }

    @Override
    public Object visit(ASTCompilationUnit cUnit, Object data) {
        assignCommentsToDeclarations(cUnit);

        return super.visit(cUnit, data);
    }

    @Override
    protected SortedMap<Integer, Node> orderedCommentsAndDeclarations(ASTCompilationUnit cUnit) {
        SortedMap<Integer, Node> itemsByLineNumber = new TreeMap<>();

        List<ASTClassOrInterfaceDeclaration> packageDecl = cUnit
                .findDescendantsOfType(ASTClassOrInterfaceDeclaration.class);
        addDeclarations(itemsByLineNumber, packageDecl);

        List<ASTEnumDeclaration> enumDecl = cUnit.findDescendantsOfType(ASTEnumDeclaration.class);
        addDeclarations(itemsByLineNumber, enumDecl);

        List<ASTAnnotationTypeDeclaration> annotationDecl = cUnit
                .findDescendantsOfType(ASTAnnotationTypeDeclaration.class);
        addDeclarations(itemsByLineNumber, annotationDecl);

        addDeclarations(itemsByLineNumber, cUnit.getComments());

        return itemsByLineNumber;
    }

    private void addDeclarations(SortedMap<Integer, Node> map, List<? extends Node> nodes) {
        for (Node node : nodes) {
            map.put((node.getBeginLine() << 16) + node.getBeginColumn(), node);
        }
    }

    /**
     * Check if node's comment contains author tag.
     *
     * @param decl node
     * @param data ruleContext
     */
    public void checkAuthorComment(AbstractJavaNode decl, Object data) {

        for (int i =0; i < CONTROLLER_FLAG.length; i ++) {
            String controllerFlag = CONTROLLER_FLAG[i];
            if (decl.getImage().endsWith(controllerFlag)) {
                Comment comment = decl.comment();
                if (null == comment) {
                    ViolationUtils.addViolationWithPrecisePosition(this, decl, data,
                            I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".comment", decl.getImage()));
                } else {
                    String commentContent = comment.getImage();
                    if (EMPTY_CONTENT_PATTERN.matcher(commentContent).matches()) {
                        ViolationUtils.addViolationWithPrecisePosition(this, decl, data,
                                I18nResources.getMessage(MESSAGE_KEY_PREFIX + ".controller",
                                        decl.getImage()));
                    }
                }
                return;
            }
        }
    }
}
